package com.pinoc.demo.randomlottery;

import cn.hutool.core.util.RandomUtil;
import org.w3c.dom.NodeList;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pinoc
 * @date 2023/11/13
 */
public class RandomLottery {

	public Prize lottery(List<Prize> prizeList) {
		prizeList.sort(Comparator.comparingInt(Prize::getWeight));
		List<Integer> weightNodeList = new ArrayList<>(Collections.singletonList(0));
		// 组装权重区间
		for (Prize prize : prizeList) {
			weightNodeList.add(weightNodeList.get(weightNodeList.size() - 1) + prize.getWeight());
		}
		int randomInt = RandomUtil.randomInt(0, weightNodeList.get(weightNodeList.size() - 1));
		for (int i = 1; i < weightNodeList.size(); i++) {
			Integer endWeight = weightNodeList.get(i);
			Integer startWeight = weightNodeList.get(i - 1);
			if (randomInt >= startWeight && randomInt < endWeight) {
				return prizeList.get(i - 1);
			}
		}
		throw new RuntimeException("程序随机数异常");
	}

	public static void main(String[] args) {
		List<Prize> prizeList = new ArrayList<>();
		prizeList.add(new Prize(0L, "奖品0", 3000));
		prizeList.add(new Prize(1L, "奖品1", 500));
		prizeList.add(new Prize(2L, "奖品2", 200));
		prizeList.add(new Prize(3L, "奖品3", 50));
		prizeList.add(new Prize(4L, "奖品4", 10));
		RandomLottery randomLottery = new RandomLottery();
		List<Prize> lotteryResult = new ArrayList<>();
		for (int i = 0; i <= 1000; i++) {
			lotteryResult.add(randomLottery.lottery(prizeList));
		}
		Map<String, List<Prize>> collect = lotteryResult.stream().collect(Collectors.groupingBy(Prize::getName));
		collect.forEach((k, v) -> System.out.println(k + " 被抽中 " + v.size() + " 次"));

	}
}
